package com.lincoln.redis.server.controller;

import com.lincoln.bean.ApiCode;
import com.lincoln.redis.server.StaticValue;
import com.lincoln.redis.server.entity.RedisValue;
import com.lincoln.redis.server.entity.User;
import com.lincoln.redis.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.*;

/**
 * redis查询
 *
 * @author lincoln
 */
@CrossOrigin
@RestController
@RequestMapping("/redis-value")
public class RedisValueController {
    @Autowired
    UserService userService;

    Jedis jedis;

    @PreAuthorize("hasAnyAuthority('ordinary','admin')")
    @GetMapping("/list")
    public ApiCode list() {
        boolean isAdmin = false;
        for (GrantedAuthority grantedAuthority : SecurityContextHolder.getContext().getAuthentication().getAuthorities()) {
            if ("admin".equals(grantedAuthority.getAuthority())) {
                isAdmin = true;
            }
        }
        String key;
        if (isAdmin) {
            key = StaticValue.USER_TABLE_HEADER + ".*_*.*";
        } else {
            User user = userService.findByName((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
            key = StaticValue.USER_TABLE_HEADER + "." + user.getId() + "_" + user.getUsername() + ".*";
        }
        Set<String> keys = jedis.keys(key);
        List<RedisValue> res = new ArrayList<>();
        for (String k : keys) {
            res.add(new RedisValue(k.replace(key.substring(0, key.length() - 2), ""), jedis.get(k)));
        }
        return ApiCode.build(res);
    }

    @PreAuthorize("hasAnyAuthority('ordinary','admin')")
    @PutMapping
    public ApiCode save(String key, String value) {
        return ApiCode.build(jedis.set(key, value));
    }
}
